<template>
    <div class="register-container">
        <div class="register-box">
            <div class="register-header">
                <img src="@/assets/img/logo.png" alt="logo" class="logo"/>
                <h2>用户注册</h2>
            </div>
            
            <el-form 
                ref="registerFormRef"
                :model="registerForm"
                :rules="registerRules"
                class="register-form"
            >
                <el-form-item prop="username">
                    <el-input 
                        v-model="registerForm.username"
                        placeholder="请输入用户名"
                        prefix-icon="User"
                    />
                </el-form-item>
                
                <el-form-item prop="password">
                    <el-input 
                        v-model="registerForm.password"
                        type="password"
                        placeholder="请输入密码"
                        prefix-icon="Lock"
                        show-password
                    />
                </el-form-item>
                
                <el-form-item prop="confirmPassword">
                    <el-input 
                        v-model="registerForm.confirmPassword"
                        type="password"
                        placeholder="请确认密码"
                        prefix-icon="Lock"
                        show-password
                    />
                </el-form-item>

                <el-form-item prop="email">
                    <el-input 
                        v-model="registerForm.email"
                        placeholder="请输入邮箱"
                        prefix-icon="Message"
                    />
                </el-form-item>

                <el-form-item prop="phone">
                    <el-input 
                        v-model="registerForm.phone"
                        placeholder="请输入手机号"
                        prefix-icon="Iphone"
                    />
                </el-form-item>
                
                <el-form-item prop="captcha">
                    <div class="captcha-container">
                    <Vcode :show="isShow" @success="success" @close="close" />
                    </div>
                </el-form-item>

                <el-form-item class="agreement">
                    <el-checkbox v-model="registerForm.agreement">
                        我已阅读并同意
                        <el-link type="primary" :underline="false">《用户协议》</el-link>
                        和
                        <el-link type="primary" :underline="false">《隐私政策》</el-link>
                    </el-checkbox>
                </el-form-item>

                <el-form-item>
                    <el-button 
                        type="primary" 
                        class="register-button"
                        :loading="loading"
                        @click="handleRegister"
                    >注册</el-button>
                </el-form-item>

                <div class="login-link">
                    已有账号？<el-link type="primary" @click="goToLogin">立即登录</el-link>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Iphone, Key } from '@element-plus/icons-vue'
import { register } from '@/api/user/user'

import Vcode from "vue3-puzzle-vcode";
const router = useRouter()
const registerFormRef = ref(null)
const loading = ref(false)
const isShow = ref(false)
const isVerified = ref(false)
const registerForm = ref({
    username: '',
    password: '',
    confirmPassword: '',
    email: '',
    phone: '',
    captcha: '',
    agreement: false
})

// 自定义校验规则
const validatePass = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入密码'))
    } else {
        if (registerForm.value.confirmPassword !== '') {
            registerFormRef.value.validateField('confirmPassword')
        }
        callback()
    }
}

const validatePass2 = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== registerForm.value.password) {
        callback(new Error('两次输入密码不一致!'))
    } else {
        callback()
    }
}

const validateAgreement = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请阅读并同意用户协议和隐私政策'))
    } else {
        callback()
    }
}

const registerRules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    password: [
        { validator: validatePass, trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    confirmPassword: [
        { validator: validatePass2, trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    agreement: [
        { validator: validateAgreement, trigger: 'change' }
    ]
}


// 验证码成功回调
const success = () => {
  isShow.value = false
  isVerified.value = true
  handleRegisterSubmit()
}

const close = () => {
  isShow.value = false
  isVerified.value = false
}

// 处理注册
const handleRegister = async () => {
    if (!registerFormRef.value) return
    
    await registerFormRef.value.validate(async (valid) => {
        if (valid) {
            isShow.value = true
        } else {
            return false
        }
    })
}

// 验证成功后的注册提交
const handleRegisterSubmit = async () => {
    try {
        loading.value = true
        const res = await register({
            username: registerForm.value.username,
            password: registerForm.value.password,
            email: registerForm.value.email,
            phone: registerForm.value.phone,
        })
        
        if (res.code === 200) {
            ElMessage.success('注册成功')
            router.push('/user/login')
        } else {
            ElMessage.error(res.message || '注册失败')
            isVerified.value = false
        }
    } catch (error) {
        console.error('注册失败：', error)
        ElMessage.error('注册失败：' + error.message)
        isVerified.value = false
    } finally {
        loading.value = false
    }
}

const goToLogin = () => {
    router.push('/user/login')
}

onMounted(() => {

})

onBeforeUnmount(() => {
    if (captchaUrl.value) {
        URL.revokeObjectURL(captchaUrl.value)
    }
})
</script>

<style scoped>
.register-container {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background: linear-gradient(135deg, #1c92d2, #f2fcfe);
}

.register-box {
    width: 400px;
    padding: 40px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.register-header {
    text-align: center;
    margin-bottom: 30px;
}

.logo {
    width: 80px;
    margin-bottom: 16px;
}

.register-header h2 {
    font-size: 24px;
    color: #303133;
    margin: 0;
}

.register-form {
    margin-top: 30px;
}

.captcha-container {
    display: flex;
    gap: 12px;
}

.captcha-img {
    height: 40px;
    cursor: pointer;
}

.agreement {
    margin-bottom: 20px;
}

.register-button {
    width: 100%;
    padding: 12px 0;
}

.login-link {
    text-align: center;
    margin-top: 16px;
    color: #606266;
}

:deep(.el-input__wrapper) {
    padding: 1px 11px;
}

:deep(.el-input__inner) {
    height: 40px;
}
</style>